﻿using command;
using Maticsoft.Model;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LXService
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer1;  //定义计时器 

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer(1000 * 59);//1000=1秒
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.AutoReset = true;//到达时间的时候执行事件； 
            timer1.Enabled = true;//设置是执行一次（false）还是一直执行(true); 
        }

        protected override void OnStop()
        {
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Thread taskerTimerThread1 = new Thread(GetLXData);
                taskerTimerThread1.Start();
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry("发生意外错误，错误内容4：" + ex.ToString());
            }
        }

        public void GetLXData()
        {
            if (DateTime.Now.Minute  == 15 || DateTime.Now.Minute == 30 || DateTime.Now.Minute == 45 || DateTime.Now.Minute == 59)
            {
                try
                {
                    Log.SaveNote("日志开始 " + DateTime.Now);

                    HttpClient Client = new HttpClient();

                    var headers = new Dictionary<string, string>
                    {
                       { "Authorization", "FN6/jhuULbmg3IFolczTsNI6XpWJeRPeiKQYDe3kCzR6WBVC6KwsJTAnkJHeBmouwMQDxgd0pgpU7/qUgYHZQA==" }
                    };

                    string reportUrl = "http://192.168.22.250:10008/dr/list-frontend";

                    DateTime dateTime = DateTime.Today.Date.AddDays(-0); // 获取当前UTC时间
                    long timestamp1 = new DateTimeOffset(dateTime).ToUnixTimeMilliseconds();

                    DateTime now = DateTime.Now; // 获取当前时间
                    DateTime startOfDay = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0); // 当天的开始时间
                    DateTime endOfLastHour = startOfDay.AddHours(23).AddMinutes(59); // 当天最后一个小时的结束时间
                                                                                     // 如果你需要的是开始时间而不是结束时间，可以减去59分钟再减去1小时
                    DateTime startOfLastHour = endOfLastHour.AddMinutes(-59).AddHours(-1).AddDays(-0);
                    long timestamp2 = new DateTimeOffset(startOfLastHour).ToUnixTimeMilliseconds();

                    List<int> ints = new List<int>();
                    ints.Add(632);
                    ints.Add(771);
                    JsonSerializerSettings settings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };

                    Maticsoft.BLL.TypeValue bllValue = new Maticsoft.BLL.TypeValue();

                    foreach (var item in ints)
                    {
                        Rootdr paramsObject = new Rootdr
                        {
                            currentPage = 0, // 当前分页页数
                            orderBy = null, // 排序的字段  如 timestamp
                            orderDirection = null, // desc | asc
                            customizedPageSize = 20, //自定义分页数 默认20
                            sortOrders = null,
                            stationNumber = item, // 站号 （必填）
                            start = timestamp1, // 开始时间戳
                            end = timestamp2, // 结束时间戳
                        };
                        string createRetJson = HttpClientUtils.DoJsonPost(paramsObject, reportUrl, headers);
                        Console.WriteLine(createRetJson);
                        createRetJson = createRetJson.Replace(" ", "");
                        Root data = JsonConvert.DeserializeObject<Root>(createRetJson);


                        if (data.code == 0 && data.results.Count > 0)
                        {
                            Maticsoft.Model.TypeValue data1 = new Maticsoft.Model.TypeValue();

                            Maticsoft.BLL.listfrontend bll = new Maticsoft.BLL.listfrontend();
                            string aaa = DateTime.Now.AddDays(-0).ToString("yyyy-MM-dd");
                            bool ii = bll.Delete(aaa, item);
                            bool delete = bllValue.Delete1(aaa, item);

                            Maticsoft.Model.listfrontend listfrontend = new Maticsoft.Model.listfrontend();
                            listfrontend.accumulateVolume = Convert.ToDecimal(data.results[0].accumulateVolume);
                            listfrontend.electricityCosume = Convert.ToDecimal(data.results[0].electricityCosume);
                            listfrontend.code = data.code;
                            listfrontend.message = data.message;
                            listfrontend.stationNumber = data.pager.stationNumber;
                            listfrontend.timestamp = data.results[0].timestamp;
                            long timestamp = data.results[0].timestamp;
                            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
                            DateTime localDateTime = dateTimeOffset.LocalDateTime;
                            listfrontend.displayTime = Convert.ToDateTime(localDateTime);
                            listfrontend.count = data.results[0].count;
                            listfrontend.vendor = data.results[0].vendor;
                            listfrontend.bitPart = data.results[0].bitPart;
                            listfrontend.deviceId = data.results[0].deviceId;
                            listfrontend.valueMapping = data.results[0].valueMapping.ToJSON();

                            data1 = JsonConvert.DeserializeObject<Maticsoft.Model.TypeValue>(listfrontend.valueMapping, settings);

                            data1.count = listfrontend.count;
                            data1.deviceId = listfrontend.deviceId;
                            data1.displayTime = listfrontend.displayTime;
                            data1.stationNumber = listfrontend.stationNumber;
                            data1.timestamp = listfrontend.timestamp;
                            int i = bll.Add(listfrontend);
                            bllValue.Add(data1);
                            Log.SaveNote("成功  " + i + "  " + item + "    " + DateTime.Now);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.SaveNote("错误" + ex.ToString() + DateTime.Now);
                }
            }
        }
        public class Rootdr
        {
            /// <summary>
            /// 当前分页页数
            /// </summary>
            public int currentPage { get; set; }
            /// <summary>
            /// 排序的字段  如 timestamp
            /// </summary>
            public string orderBy { get; set; }
            /// <summary>
            /// desc | asc
            /// </summary>
            public string orderDirection { get; set; }
            /// <summary>
            /// 自定义分页数 默认20
            /// </summary>
            public int customizedPageSize { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string sortOrders { get; set; }
            /// <summary>
            /// 站号 （必填）
            /// </summary>
            public int stationNumber { get; set; }
            /// <summary>
            /// 开始时间戳
            /// </summary>
            public long start { get; set; }
            /// <summary>
            /// 结束时间戳
            /// </summary>
            public long end { get; set; }
        }
    }
}
